package exer;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

/**
 * @author tongchen
 * @create 2023-02-08 16:21
 */
public class CountDownLatchTest {
    public static void main(String[] args) throws InterruptedException {
        //创建10个任务
        CountDownLatch countDownLatch = new CountDownLatch(10);
        Runnable runnable=new Runnable() {
            @Override
            public void run() {
                //准备就绪
                System.out.println(Thread.currentThread().getName()+"准备就绪");
                //开始运行
                System.out.println(Thread.currentThread().getName()+"开始运行");
                try {
                    TimeUnit.SECONDS.sleep(2);
                    System.out.println(Thread.currentThread().getName()+"运行结束");
                    countDownLatch.countDown();

                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        };
        for (int i = 0; i < 10; i++) {
            Thread thread=new Thread(runnable,"任务"+i);
            thread.start();
        }
        //等待任务全部执行结束
        countDownLatch.await();
        System.out.println("任务全部执行结束了......");
    }
}
